package com.guyu.common.web.condition;

import cn.hutool.core.util.StrUtil;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;
import java.util.Objects;

public class NeProfilesCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String activeProfile = environment.getProperty("spring.profiles.active");
        if (StrUtil.isBlank(activeProfile)) {
            return false;
        }
        // 如果 activeProfile 是逗号分隔的多个值，拆分成数组
        String[] activeProfilesArray = activeProfile.split(",");

        // 获取注解中定义的值
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalNeProfiles.class.getName());
        if (Objects.isNull(annotationAttributes)) {
            return false;
        }
        String[] requiredProfiles = (String[]) annotationAttributes.get("value");
        // 检查是否匹配
        for (String profile : activeProfilesArray) {
            for (String requiredProfile : requiredProfiles) {
                if (profile.trim().equals(requiredProfile.trim())) {
                    return false;
                }
            }
        }
        return true;
    }


}
